<?php get_header(); ?>

<?php
$aOptions = SofaSuppaStore::initOptions( false );
$entrycurrency = $aOptions[ 'entrycurrency' ];
$prod_use_related = $aOptions[ 'prod_use_related' ];
$prod_disable_comments = $aOptions[ 'prod_disable_comments' ];
$num_of_mb = $aOptions[ 'num_of_def_boxes' ];
$use_stock = $aOptions[ 'use_stock' ];
if( $num_of_mb <= 0 ) $num_of_mb = 1;
?>

<!-- main content start -->
    
	<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    
    <?php
	// meta stuff
	$arr_price = array();
	$arr_sizes = array();
	$arr_stock = array();
	$arr_shipp = array();
	$iter_meta = 0;
	// extract post meta
	while( $iter_meta < $num_of_mb ) {
		$single_price = 'sofa_' . $iter_meta . '_textarea_price';
		$single_sizes = 'sofa_' . $iter_meta . '_textarea_size';
		$single_stock = 'sofa_' . $iter_meta . '_textarea_stock';
		$single_shipp = 'sofa_' . $iter_meta . '_textarea_shipp';
		// populate array
		$single_id = get_the_ID(); // just to speed it up
		if( get_post_meta( $single_id, $single_price, true ) != '*' ) {
			array_push( $arr_price, get_post_meta( $single_id, $single_price, true ) );
			array_push( $arr_sizes, get_post_meta( $single_id, $single_sizes, true ) );
			if( $use_stock == 'yes' ) {
				$stock_post_meta_value = get_post_meta( $single_id, $single_stock, true );
				if( $stock_post_meta_value == '*' ) array_push( $arr_stock, 0 );
				else array_push( $arr_stock, $stock_post_meta_value );
			}
			if( get_post_meta( $single_id, $single_shipp, true ) != '*' ) array_push( $arr_shipp, get_post_meta( $single_id, $single_shipp, true ) );
		}
		
		$iter_meta ++;
	}
	// content
	$content = get_the_content();
	$content = apply_filters( 'the_content', $content );
	$content = str_replace( ']]>', ']]&gt;', $content );
	$content = preg_replace( '|(class=[\'"]wp-caption.*?[\'"]).*?(style=[\'"](.*?)[\'"]).*?|i', '$1', $content ); // remove captions from extracted images
	$p_page = __( "Previous page", "sofa_suppastore" );
	$n_page = __( "Next page", "sofa_suppastore" );
	wp_link_pages( array( 'before' => '<div id="pagination" class="wp-pagenavi grid_8 alpha omega"><span class="nava">', 'next_or_number' => 'next', 'previouspagelink' => $p_page, 'nextpagelink' => $n_page, 'after' => '</span></div>' ) );
	?>
    
    <!-- content start -->

    <div id="featured" class="grid_8">
    
    	<!-- title start -->
    
        <h1 class="grid_8 alpha"><?php the_title(); ?></h1>
        
        <!-- title end -->
        
        <!-- images set start -->
        
        <div id="prodimageset" class="castshadow grid_4 alpha">
        
        	<?php
			// any featured image?
			if( has_post_thumbnail() && get_the_post_thumbnail( $single_id, 'featured' ) != '' ) {
				$featured_image_id = get_post_thumbnail_id();
				$large_image_url = wp_get_attachment_image_src( $featured_image_id, 'large' );
				echo '<div class="grid_4 alpha omega">';
				echo '<a href="' . $large_image_url[ 0 ] . '" title="' . the_title_attribute( 'echo=0' ) . '">';
				the_post_thumbnail( 'featured' );
				echo '</a>';
				echo '</div>';
			}
			?>
        
        </div>
        
        <!-- images set end -->
        
        <!-- product selection start -->
        
        <div id="proddetails" class="grid_4 omega">
        
        <h1 id="prodprice"><?php echo $entrycurrency . ' ' . number_format( $arr_price[ 0 ], 2, '.', '' ); ?></h1>
        
        	<table id="tblmeta" width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <th scope="col" class="textleft"><?php _e( "Size", "sofa_suppastore" ); ?></th>
                <th scope="col" class="<?php if( empty( $arr_shipp ) && $use_stock == 'no' ) echo 'textright'; else echo 'center'; ?>"><?php echo __( "Price", "sofa_suppastore" ) . ' ' . '(' . $entrycurrency . ')'; ?></th>
                <?php if( !empty( $arr_shipp ) ) { ?><th scope="col" class="<?php if( $use_stock == 'no' ) echo 'textright'; else echo 'center'; ?>"><?php echo __( "Shipping", "sofa_suppastore" ) . ' ' . '(' . $entrycurrency . ')'; ?></th><?php } ?>
                <?php if( $use_stock == 'yes' ) { ?><th scope="col" class="textright"><?php _e( "Stock", "sofa_suppastore" ); ?></th><?php } ?>
              </tr>
              
              <?php
			  	// loop through meta
				$iter_chck = 0;
				$iter_loop = 0;
				$iter_leng = count( $arr_price );
				while( $iter_loop < $iter_leng ) {
					if( $use_stock == 'yes' ) {
						if( $arr_stock[ $iter_loop ] != '*' && $arr_stock[ $iter_loop ] > 0 ) { // don't list products that are out of stock!
							$iter_chck ++;
							echo '<tr id="infoline_' . $iter_loop . '" class="proddetailstr">';
							echo '<td title="size" class="optionstill textleft">' . $arr_sizes[ $iter_loop ] . '</td>';
							echo '<td title="price" class="center">' . number_format( $arr_price[ $iter_loop ], 2, '.', '' ) . '</td>';
							if( !empty( $arr_shipp ) ) echo '<td title="shipp" class="center">' . number_format( $arr_shipp[ $iter_loop ], 2, '.', '' ) . '</td>';

							$true_stock_value = 0; 
							if( $arr_stock[ $iter_loop ] != '*' ) $true_stock_value = $arr_stock[ $iter_loop ];
							echo '<td title="stock" class="textright">' . $true_stock_value . '</td>'; 
							
							echo '</tr>';
						}
					} elseif( $use_stock == 'no' ) {
						$iter_chck ++;
						echo '<tr id="infoline_' . $iter_loop . '" class="proddetailstr">';
						echo '<td title="size" class="optionstill textleft">' . $arr_sizes[ $iter_loop ] . '</td>';
						if( !empty( $arr_shipp ) ) echo '<td title="price" class="center">' . number_format( $arr_price[ $iter_loop ], 2, '.', '' ) . '</td>';
						else echo '<td title="price" class="textright">' . number_format( $arr_price[ $iter_loop ], 2, '.', '' ) . '</td>';
						if( !empty( $arr_shipp ) ) echo '<td title="shipp" class="textright">' . number_format( $arr_shipp[ $iter_loop ], 2, '.', '' ) . '</td>';
						echo '</tr>';
					}
					
					$iter_loop ++;
					
				}
				if( $iter_chck == 0 ) {
					echo '<tr>';
					echo '<td colspan="4" class="textleft">' . __( "Product not available!", "sofa_suppastore" ) . '</td>';
					echo '</tr>';
				}
			  ?>
              
            </table>
            
            <form id="buyme" method="post" action="<?php echo get_template_directory_uri() . '/cart_handler.php'; ?>">
            
                <?php if( $iter_chck > 0 ) { ?>
                
                <div class="grid_4 alpha omega">
                
                    <div class="left"><span class="qty"><?php _e( "Quantity", "sofa_suppastore" ); ?> </span><input type="text" name="itemqty" id="itemqty" value="1" /></div>
                    <div class="right"><button class="add-to-cart" type="submit" tabindex="2"><?php _e( "Add to Cart", "sofa_suppastore" ); ?></button></div>
                    
                </div>
                
                <?php } ?>
                
                <input type="hidden" name="itemselmeta" id="itemselmeta" value="" />
                <input type="hidden" name="itemid" id="itemid" value="<?php the_ID(); ?>" />
                <input type="hidden" name="dothis" id="dothis" value="addnew" />
                <input type="hidden" name="itemsize" id="itemsize" value="" />
                <input type="hidden" name="itemprice" id="itemprice" value="" />
                <input type="hidden" name="itemstock" id="itemstock" value="" />
                <input type="hidden" name="itemshipp" id="itemshipp" value="" />
                <?php wp_nonce_field( 'chck_ref_cc', 'sofa_suppastore_cc' ); ?>
            
            </form>
            
            <!-- product selection end -->
        
        </div>
        
        <!-- product description start -->
        
        <div class="grid_8 alpha omega">
        
            <?php
			// get all other images attached to this product...
			$html_tab_images = '';
			$args = array(
				'post_type' => 'attachment',
				'numberposts' => -1,
				'post_status' => NULL,
				'post_parent' => $single_id,
				'exclude' => get_post_thumbnail_id()
				); 
			$attachments = get_posts( $args );
			
			if( $attachments ) {
				$i = 1;
				$html_tab_images .= '<div id="pimages" class="tab-content">';
				foreach( $attachments as $attachment ) {
					if( $i % 4 == 0 ) $switch_class = ' alpha omega';
					elseif( ( $i - 1 ) % 4 == 0 ) $switch_class = '';
					else $switch_class = '';
					$large_image_url = wp_get_attachment_image_src( $attachment->ID, 'large' );
					$html_tab_images .= '<span style="width: 130px;" class="prodimgwrap alignleft' . $switch_class . '"><a href="' . $large_image_url[ 0 ] . '" title="' . the_title_attribute( 'echo=0' ) . '">';
					$html_tab_images .= wp_get_attachment_image( $attachment->ID, 'thumbnail' );
					$html_tab_images .= '</a><span class="imgshadow"><span class="shadowleft">&nbsp;</span><span class="shadowright">&nbsp;</span></span></span>';
					$i ++;
				}
				echo '</div>';
			}
			?>
        
        	<span class="prodtab"><a class="tablink tabactive" href="javascript:;" rel="pdetails"><?php _e( "Product Details", "sofa_suppastore" ); ?></a></span>
            
            <?php if( $attachments ) { ?><span class="prodtab"><a class="tablink tabnormal" href="javascript:;" rel="pimages"><?php _e( "More Images", "sofa_suppastore" ); ?></a></span><?php } ?>
            
            <div id="pdetails" class="tab-content defaulttab">
        
            <?php
            // remove images from content
            $content = preg_replace( '|<a.*?href=[\'"](.*?)[\'"].*?>.*?<img.*?src=[\'"](.*?)[\'"].*?alt=[\'"](.*?)[\'"].*?><.*?a>|i', '', $content );
            echo $content;
            ?>
            
            </div>
            
            <?php echo $html_tab_images; ?>
            
        </div>
        
        <!-- product description end -->
        
        <!-- content end -->
        
        <!-- related products scroller start -->
        
        <?php
		if( $prod_use_related == 'yes' ) {
		// handle related products...
		$backup = $post; // backup the current object
		$tags = wp_get_post_tags( $single_id );
		$tagIDs = array();
		if( $tags ) {
			$tagcount = count( $tags );
			for( $i = 0; $i < $tagcount; $i++ ) {
				$tagIDs[ $i ] = $tags[ $i ]->term_id;
			}
			$args = array(
				'tag__in' => $tagIDs,
				'post__not_in' => array( $single_id ),
				'showposts' => -1,
				'post_type' => 'product'
			);
			$my_query = new WP_Query( $args );
			// how many related posts? $my_query->post_count;
			if( $my_query->have_posts() ) : 
		?>
        
        <div class="clear">&nbsp;</div>
        
        <div id="relatedproducts" class="castshadow grid_8 alpha">
        
        	<div class="bordertop grid_8 alpha omega">
            
            	<!-- control button left start -->
        
                <div class="grid_2 alpha">
                	<?php if( $my_query->post_count > 4 ) { ?>
                    <span class="addtocart prevPage"><a href="#l"><?php _e( "Previous", "sofa_suppastore" ); ?></a></span>
                    <?php } else echo '&nbsp;'; ?>
                </div>
                
                <!-- control button left end -->
                
                <!-- title start -->
                
                <div class="grid_4 center">
                    <h2 class="relatedtitle"><?php _e( "Related products", "sofa_suppastore" ); ?></h2>
                </div>
                
                <!-- title end -->
                
                <!-- control button right start -->
                
                <div class="grid_2 omega">
                	<?php if( $my_query->post_count > 4 ) { ?>
                    <span class="addtocart nextPage"><a href="#r"><?php _e( "Next", "sofa_suppastore" ); ?></a></span>
                    <?php } else echo '&nbsp;'; ?>
                </div>
                
                <!-- control button right end -->
                
            </div>
            
            <div class="scrollable">
            
            	<ul class="images items">
                
                	<!-- wordpress sub-loop loop start -->
                
                	<?php
					$count_items = 0;
					while( $my_query->have_posts() ) : $my_query->the_post();
					
					// related post details
					$rel_product_meta_labeltype  = get_post_meta( $post->ID, 'labeltype', true );
					$rel_product_meta_labelvalue = get_post_meta( $post->ID, 'labelvalue', true );
					$rel_product_meta_price      = get_post_meta( $post->ID, 'sofa_0_textarea_price', true );
					
					// extract image
					$rel_prod_image_link = '';
					if( has_post_thumbnail( $post->ID ) ) {
						$default_attr = array( 'class' => "size-thumbnail clearfix alignleft", 'alt' => $post->post_title, 'title' => $post->post_title );
						if( $rel_product_meta_labeltype != '' && $rel_product_meta_labelvalue != '' ) {
							$rel_prod_image_link .= ( '<a href="' . get_permalink( $post->ID ) . '" rel="' . $rel_product_meta_labeltype . '|' . $rel_product_meta_labelvalue . '">' );
						} else $rel_prod_image_link .= ( '<a href="' . get_permalink( $post->ID ) . '">' );
						$rel_prod_image_link .= get_the_post_thumbnail( $post->ID, 'thumbnail', $default_attr );
						$rel_prod_image_link .= '</a>';
					}
					?>
                
                	<li>
                        <div class="grid_2 product alpha">
                            <?php echo $rel_prod_image_link; ?>
                            <span class="prodtitle clearfix">
                            	<?php echo $post->post_title; ?>
                            </span>
                        </div>
                    </li> 

					<?php
                    endwhile; 
					// backup query aka reset custom query posts loop
                    $post = $backup;
                    wp_reset_query();
                    ?>
                    
                    <!-- wordpress sub-loop loop end -->

                </ul>
                    
            </div>
        
        </div>
        
        <!-- related products scroller end -->
        
		<?php 
			endif; 
		} // end if tags
		} // end if use related
		?>
        
        <?php endwhile; ?>
        
        <script type="text/javascript">
        
        jQuery( document ).ready( function() {
			
			// tabs
			jQuery( '.prodtab a' ).click( function() {
				if( !jQuery( this ).is( '.tabactive' ) ) switch_tabs( jQuery( this ) );
			} );
            
            // related products - Scrollable
            <?php if( $prod_use_related == 'yes' ) { if( $tags ) { ?>jQuery( "div.scrollable" ).scrollable( { size: 4, speed: 300 } );<?php } } ?>
            
            // table tr hover
            jQuery( function() {
                jQuery( 'table .proddetailstr' ).hover( function() {
                    jQuery( this ).addClass( 'hovered' );
                    jQuery( this ).css( 'cursor', 'default' );
                }, 
                function() {
                    jQuery( this ).removeClass( 'hovered' );
                } )
            } );
			
			// colorbox
			// jQuery( "a[rel='productslide']" ).colorbox( { transition: "fade" } );
            
            // anything already written to fields (browser cache?)
            var written_meta  = decodeURIComponent( jQuery( '#itemselmeta' ).val() );
            var written_price = jQuery( '#itemprice' ).val();
            if( written_meta != '' ) jQuery( written_meta + ' td:first-child' ).removeClass( 'optionstill' ).addClass( 'optionactiv' );
            else {
				jQuery( '#infoline_0 td:first-child' ).removeClass( 'optionstill' ).addClass( 'optionactiv' );
				// populate other crucial info with initial values
				jQuery( '#itemselmeta' ).val( '%23infoline_0' );
				jQuery( '#itemsize' ).val( "<?php echo $arr_sizes[ 0 ]; ?>" );
				jQuery( '#itemprice' ).val( "<?php echo $arr_price[ 0 ]; ?>" );
				<?php if( $use_stock == 'yes' ) { ?>jQuery( '#itemstock' ).val( "<?php echo $arr_stock[ 0 ]; ?>" );<?php } ?>
				<?php if( !empty( $arr_shipp ) ) { ?>jQuery( '#itemshipp' ).val( "<?php echo $arr_shipp[ 0 ]; ?>" );<?php } ?>
			}
            if( written_price != '' ) jQuery( '#prodprice' ).html( "<?php echo $entrycurrency . ' '; ?>" + written_price );
            
            // handle selections
            jQuery( '.proddetailstr' ).click( function( event ) {
                var this_id = '#' + jQuery( this ).attr( 'id' );
                var options_length = jQuery( this_id + ' td' ).length;
                if( options_length > 0 ) {
                    var ii = 0;
                    while( ii < options_length ) { // faster than jQuery.each
                        var cell_value = jQuery( this_id + ' td' ).eq( ii ).text();
                        var cell_title = jQuery( this_id + ' td' ).eq( ii ).attr( 'title' );
                        switch( cell_title ) {
                            case 'size': jQuery( '#itemsize' ).val( encodeURIComponent( cell_value ) );
                            break;
                            case 'price': jQuery( '#itemprice' ).val( encodeURIComponent( cell_value ) );
                            break;
							<?php if( $use_stock == 'yes' ) { ?>
                            case 'stock': jQuery( '#itemstock' ).val( encodeURIComponent( cell_value ) );
                            break;
							<?php } ?>
							<?php if( !empty( $arr_shipp ) ) { ?>
                            case 'shipp': jQuery( '#itemshipp' ).val( encodeURIComponent( cell_value ) );
                            break;
							<?php } ?>
                            default: 0;
                        }
                        ii ++;
                    }
                    
                    // remember selection
                    if( jQuery( this ).attr( 'id' ).substring( 0, 8 ) == 'infoline' ) jQuery( '#itemselmeta' ).val( encodeURIComponent( this_id ) );
                    
                    // remove all active selections
                    var my_parent = '#' + jQuery( this_id ).parent().parent().attr( 'id' );
                    jQuery( my_parent + ' tr td:first-child' ).each( function() {
                        jQuery( this ).removeClass( 'optionactiv' ).addClass( 'optionstill' );
                    } );
                    
                    // switch class to selected
                    jQuery( this_id + ' td:first-child' ).removeClass( 'optionstill' ).addClass( 'optionactiv' );
                    
                    // update main price
                    jQuery( '#prodprice' ).html( "<?php echo $entrycurrency . ' '; ?>" + jQuery( '#itemprice' ).val() );
                }
            } );
        } );
		
		function switch_tabs( obj ) {
			
			jQuery( '.tab-content' ).slideUp( 'fast', function() { jQuery( '#' + obj.attr( "rel" ) ).slideDown( 'fast' ); } );
			jQuery( '.prodtab a' ).removeClass( 'tabactive' );
			obj.addClass( 'tabactive' );
			
		}
        
        </script>
        
    <!-- comments -->
    <?php if( 'open' == $post->comment_status && $prod_disable_comments == 'no' ) comments_template(); ?>
    <!-- end comments -->
        
    </div>
    
    <?php else: ?>
    
    <!-- no content start -->
    
    <div id="featured" class="castshadow grid_8">
    
        <div class="grid_8 alpha">
        	<h1><?php _e( "Nothing found!", "sofa_suppastore" ); ?></h1>
            <p><?php _e( "Sorry but no products found. Take your time, there's gonna be soon to see something listed here.", "sofa_suppastore" ); ?></p>
        </div>
        
    </div>
    
    <!-- no content end -->
    
	<?php endif; ?>
    
<!-- main content end -->

<!-- include sidebar start -->
    
    <?php get_template_part( 'sidebar_single_product' ); ?>
    
<!-- include sidebar end -->

<?php get_footer(); ?>

